package com.shundr.shipper.user;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.crypto.spec.IvParameterSpec;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseActivity;
import com.shundr.shipper.common.DetailAreaGridActivity;
import com.shundr.shipper.common.model.PictureInfo;
import com.shundr.shipper.common.util.Base64Util;
import com.shundr.shipper.common.util.JsonUtil;
import com.shundr.shipper.common.util.LImageLoader;
import com.shundr.shipper.common.util.PictureUtil;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.frame.constant.LConstants;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.util.LLogger;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.user.http.UserRequest;
import com.shundr.shipper.user.model.CompanyInfo;
import com.shundr.shipper.user.model.UserInfo;
import com.shundr.shipper.user.util.UserUtil;

/**
 * 企业认证
 * AuthCompanyActivity
 * 
 * @author larry 2015-6-29 下午4:05:11 
 * @version 1.0.0
 *
 */
public class CompanyReAuthActivity extends BaseActivity implements OnClickListener {

	private TextView tvStatus;
	
	private EditText etCompanyName;
	private EditText etCompanyAddress;
	private String addressCode = "";
	private EditText et_company_address_2;
	private EditText etPhone;

	private RelativeLayout layoutLicenceCard;
	private RelativeLayout layoutBussCard;//名片
	private RelativeLayout layoutDoorCard;//门头照
	
	private ImageView btnLicenceCard;
	private ImageView btnBussCard;//名片
	private ImageView btnDoorCard;//门头照
	
	private Button btnConfirm;
	
	private PictureInfo mLicenceInfo;// 营业执照
	private PictureInfo mBussInfo;// 名片
	private PictureInfo mDoorInfo;// 门头照

	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();

	private int flag = 0;
	/**
	 * 是否提交认证
	 */
	private boolean dot=false;
	private int companyId;

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESULT = 3;// 结果
	public static final int GET_AREA = 502;// 选择地址
	public static final String IMAGE_UNSPECIFIED = "image/*";
	
	private int mCompanyStatus = 0;
	
	private CompanyInfo mCompanyInfo;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case UserRequest.COMMIT_COMPANY_RE_AUTH_SUCCESSED:
				dot=true;
				ToastHelper.toastLong(mContext, "个人认证提交成功,会在一个工作日内审核,请耐心等待");
				new UserRequest(mContext, mHandler).getUserInfoByToken();
				new Timer().schedule(new TimerTask() {
					
					@Override
					public void run() {
						setResult(501);
						finish();
					}
				}, 1000);
				break;
			case UserRequest.GET_COMPANY_INFO_SUCCESSED:
				CompanyInfo companyInfo = (CompanyInfo) msg.obj;
				initData(companyInfo);
				ProgressDialogHelper.dismiss();
				break;
			case UserRequest.GET_USER_DETAIL_INFO_SUCCESSED:
				UserInfo userInfo = (UserInfo) msg.obj;
				UserUtil.saveUserToLocal(mContext, userInfo, null);
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, (String) msg.obj);
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_auth_cargo);

		tvStatus = (TextView)findViewById(R.id.tv_status);
		UserInfo userInfo = LContext.getUserInfo(mContext);
		if(userInfo.getCompanyValidationStatus() == 1){
			tvStatus.setVisibility(View.VISIBLE);
			tvStatus.setText("审核中");
		}else if(userInfo.getCompanyValidationStatus() == 2){
			tvStatus.setVisibility(View.VISIBLE);
			tvStatus.setText("审核通过");
		}else if(userInfo.getCompanyValidationStatus() == 3){
			tvStatus.setVisibility(View.VISIBLE);
			tvStatus.setText(userInfo.getCompanyValidationMsg());
		}
		
		etCompanyName = (EditText) findViewById(R.id.et_company_name);
		etCompanyAddress = (EditText) findViewById(R.id.et_company_address);
		et_company_address_2 = (EditText) findViewById(R.id.et_company_address_2);
		etPhone = (EditText) findViewById(R.id.et_phone);
		
		layoutLicenceCard = (RelativeLayout) findViewById(R.id.layout_license_card);
		layoutBussCard = (RelativeLayout) findViewById(R.id.layout_buss_card);
		layoutDoorCard = (RelativeLayout) findViewById(R.id.layout_door_card);

		btnLicenceCard = (ImageView) findViewById(R.id.btn_license);
		btnBussCard = (ImageView) findViewById(R.id.btn_buss_card);
		btnDoorCard = (ImageView) findViewById(R.id.btn_door_card);
		btnConfirm = (Button)findViewById(R.id.btn_confirm);
		
		btnConfirm.setOnClickListener(this);
		btnConfirm.setVisibility(View.GONE);
		
		layoutLicenceCard.setOnClickListener(this);
		layoutBussCard.setOnClickListener(this);
		layoutDoorCard.setOnClickListener(this);

		btnLicenceCard.setOnClickListener(this);
		btnBussCard.setOnClickListener(this);
		btnDoorCard.setOnClickListener(this);

		etCompanyAddress.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent start = new Intent(mContext,DetailAreaGridActivity.class);
				start.putExtra("title", "选择公司地址");
				startActivityForResult(start, GET_AREA);
			}
		});
		
		mCompanyStatus = LContext.getUserInfo(mContext).getCompanyValidationStatus();

		ProgressDialogHelper.show(mContext);
		new UserRequest(mContext, mHandler).getCompanyInfo();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("flag", flag);
		outState.putString("addressCode", addressCode);
		outState.putSerializable("mLicenceInfo", mLicenceInfo);
		outState.putSerializable("mBussInfo", mBussInfo);
		outState.putSerializable("mDoorInfo", mDoorInfo);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		flag = savedInstanceState.getInt("flag");
		addressCode = savedInstanceState.getString("addressCode");
		mLicenceInfo = (PictureInfo) savedInstanceState.getSerializable("mLicenceInfo");
		
		if (mLicenceInfo != null) {
			ImageLoader.getInstance().displayImage("file://" + mLicenceInfo.getFilename(), btnLicenceCard,LImageLoader.mOptions);
		}
		mBussInfo = (PictureInfo) savedInstanceState.getSerializable("mBussInfo");
		
		if (mBussInfo != null) {
			ImageLoader.getInstance().displayImage("file://" + mBussInfo.getFilename(), btnBussCard,LImageLoader.mOptions);
		}
		mDoorInfo = (PictureInfo) savedInstanceState.getSerializable("mDoorInfo");
		
		if (mDoorInfo != null) {
			ImageLoader.getInstance().displayImage("file://" + mDoorInfo.getFilename(), btnDoorCard,LImageLoader.mOptions);
		}
		clearFocus();
	}
	
	private void initData(CompanyInfo info){
		try {
			if(info == null)
				return;
			mCompanyInfo = info;
			companyId = info.getCompanyId();
			etCompanyName.setText(info.getCompanyName());
			etCompanyAddress.setText(info.getCompanyCity());
			et_company_address_2.setText(info.getCompanyAddress());
			etPhone.setText(info.getCompanyTelephone());
			addressCode = info.getCompanyCityCode() + "";
			
			if(mCompanyStatus != 0 && mCompanyStatus != 3){
				etCompanyName.setEnabled(false);
				if(!StringUtil.isNull(info.getCompanyBusinessCardPic())){
					layoutBussCard.setClickable(false);
				}else{
					layoutBussCard.setClickable(true);
				}
				if(!StringUtil.isNull(info.getCompanyBusinessPic())){
					layoutLicenceCard.setClickable(false);
				}else{
					layoutLicenceCard.setClickable(true);
				}
			}else{
				etCompanyName.setEnabled(true);
				layoutLicenceCard.setClickable(true);
				layoutBussCard.setClickable(true);
			}
			
			btnConfirm.setVisibility(View.VISIBLE);
			
			ImageLoader.getInstance().displayImage(info.getCompanyBusinessPic(), btnLicenceCard,LImageLoader.mOptions);
			ImageLoader.getInstance().displayImage(info.getCompanyBusinessCardPic(), btnBussCard,LImageLoader.mOptions);
			ImageLoader.getInstance().displayImage(info.getCompanyDoorPic(), btnDoorCard,LImageLoader.mOptions);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onDestroy() {
		if (dot) {
			setResult(333);
		}
		super.onDestroy();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Uri data2 = null;
			if (data == null) {
				data2 = PictureUtil.getImageUri();
			} else {
				data2 = data.getData();
			}
			String outPic = "";
			if (resultCode == RESULT_OK) {
				try {
					switch (requestCode) {
					case PictureUtil.PHOTO_PICKED_WITH_DATA:
						outPic = PictureUtil.getRealFilePath(mContext, data2);
						outPic = PictureUtil.compressJpgImage(outPic);
						break;
					case PictureUtil.CAMERA_WITH_DATA:
						outPic = PictureUtil.compressJpgImage(LConstants.TEMP_PIC_PATH);
						break;
					case PictureUtil.PHOTO_CROP:
						break;
					default:
						break;
					}
					
					if (!new File(outPic).exists()) {
						ToastHelper.toastShort(mContext, getResources().getString(R.string.image_error));
						return;
					}
					
					Bitmap bitmap = BitmapFactory.decodeFile(outPic);
					PictureInfo info = new PictureInfo();
					info.setFileBase64Body(Base64Util.encodeImage(bitmap));
					info.setFilename(outPic);
					bitmap.recycle();
					
					if (flag == 0) {
						info.setType(PictureInfo.FileType.company);
						mLicenceInfo = info;
						ImageLoader.getInstance().displayImage("file://" + outPic, btnLicenceCard, LImageLoader.mOptions);
					}else if (flag == 1){
						info.setType(PictureInfo.FileType.card);
						mBussInfo = info;
						ImageLoader.getInstance().displayImage("file://" + outPic, btnBussCard, LImageLoader.mOptions);
					}else if (flag == 2){
						info.setType(PictureInfo.FileType.door);
						mDoorInfo = info;
						ImageLoader.getInstance().displayImage("file://" + outPic, btnDoorCard, LImageLoader.mOptions);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} 
		}else if (resultCode == GET_AREA) {
			if (data != null) {
				try {
					String addr = data.getStringExtra("addr");
					etCompanyAddress.setText(addr);
					addressCode = data.getStringExtra("areaCode");
					LLogger.e(addr + " " + addressCode);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			if (check()) {
				ProgressDialogHelper.show(mContext, "正在提交认证,请稍后...");
				mPictures.clear();
				if (mLicenceInfo != null) {
					mPictures.add(mLicenceInfo);
				}
				if (mBussInfo != null) {
					mPictures.add(mBussInfo);
				}
				if (mDoorInfo != null) {
					mPictures.add(mDoorInfo);
				}
				String json = JsonUtil.toJson(mPictures);
				LLogger.e(json);
				new UserRequest(mContext, mHandler).commitCompanyReAuth(companyId,
						etCompanyName.getText().toString(), etCompanyAddress
								.getText().toString(), addressCode,
						et_company_address_2.getText().toString(), etPhone
								.getText().toString(), json);
			}
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void clearFocus(){
		et_company_address_2.clearFocus();
		etCompanyAddress.clearFocus();
		etCompanyName.clearFocus();
		etPhone.clearFocus();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_license:
			try {
				if (mLicenceInfo != null) {
					ArrayList<String> list = new ArrayList<String>();
					if (!StringUtil.isNull("file://" + mLicenceInfo.getFilename())) {
						list.add("file://" + mLicenceInfo.getFilename());
					}
					if (list.size() > 0) {
						openImageReview(mContext, 0, list);
					}
				}else{
					if (mCompanyInfo != null) {
						ArrayList<String> list = new ArrayList<String>();
						if (!StringUtil.isNull(mCompanyInfo.getCompanyBusinessPic())) {
							list.add(mCompanyInfo.getCompanyBusinessPic());
						}
						if (list.size() > 0) {
							openImageReview(mContext, 0, list);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.btn_buss_card:
			try {
				if (mBussInfo != null) {
					ArrayList<String> list = new ArrayList<String>();
					if (!StringUtil.isNull("file://" + mBussInfo.getFilename())) {
						list.add("file://" + mBussInfo.getFilename());
					}
					if (list.size() > 0) {
						openImageReview(mContext, 0, list);
					}
				}else{
					if (mCompanyInfo != null) {
						ArrayList<String> list = new ArrayList<String>();
						if (!StringUtil.isNull(mCompanyInfo.getCompanyBusinessCardPic())) {
							list.add(mCompanyInfo.getCompanyBusinessCardPic());
						}
						if (list.size() > 0) {
							openImageReview(mContext, 0, list);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.btn_door_card:
			try {
				if (mDoorInfo != null) {
					ArrayList<String> list = new ArrayList<String>();
					if (!StringUtil.isNull("file://" + mDoorInfo.getFilename())) {
						list.add("file://" + mDoorInfo.getFilename());
					}
					if (list.size() > 0) {
						openImageReview(mContext, 0, list);
					}
				}else{
					if (mCompanyInfo != null) {
						ArrayList<String> list = new ArrayList<String>();
						if (!StringUtil.isNull(mCompanyInfo.getCompanyDoorPic())) {
							list.add(mCompanyInfo.getCompanyDoorPic());
						}
						if (list.size() > 0) {
							openImageReview(mContext, 0, list);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.layout_license_card:
			flag = 0;
			PictureUtil.doPickPhotoAction(this);
			break;
		case R.id.layout_buss_card:
			flag = 1;
			PictureUtil.doPickPhotoAction(this);
			break;
		case R.id.layout_door_card:
			flag = 2;
			PictureUtil.doPickPhotoAction(this);
			break;
		case R.id.btn_confirm:
			if (check()) {
				ProgressDialogHelper.show(mContext, "正在提交认证,请稍后...");
				mPictures.clear();
				if (mLicenceInfo != null) {
					mPictures.add(mLicenceInfo);
				}
				if (mBussInfo != null) {
					mPictures.add(mBussInfo);
				}
				if (mDoorInfo != null) {
					mPictures.add(mDoorInfo);
				}
				String json = JsonUtil.toJson(mPictures);
				LLogger.e(json);
				new UserRequest(mContext, mHandler).commitCompanyReAuth(companyId,
						etCompanyName.getText().toString(), etCompanyAddress
								.getText().toString(), addressCode,
						et_company_address_2.getText().toString(), etPhone
								.getText().toString(), json);
			}
			break;
		default:
			break;
		}
	}

	private boolean check() {
		// company name is needed
		if (StringUtil.isNull(etCompanyName.getText().toString().trim())) {
			etCompanyName.requestFocus();
			ToastHelper.toastShort(mContext, "请输入公司名称");
			return false;
		}
		if (StringUtil.isNull(etCompanyAddress.getText().toString().trim())
				&& StringUtil.isNull(et_company_address_2.getText().toString()
						.trim())) {
			et_company_address_2.requestFocus();
			ToastHelper.toastShort(mContext, "请输入公司地址");
			return false;
		}

		return true;
	}
	
}
